package com.zhao.controller.show;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.Util.HttpContextUtil;
import com.zhao.Util.IPUtil;
import com.zhao.Util.WalletUtil;
import com.zhao.comm.log.MyLog;
import com.zhao.pojo.*;
import com.zhao.service.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/show")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    StatisticService statisticService;
    @Autowired
    WalletService walletService;
    @Autowired
    ArticleService articleService;
    @Autowired
    UserService userService;

    @ResponseBody
    @RequestMapping("/comment")
    public String addComment(Comment comment){
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        User loginUser = (User) SecurityUtils.getSubject().getPrincipal();
        comment.setAuthor(loginUser.getUserAccount());
        if (comment.getIp().isEmpty()){
            comment.setIp(IPUtil.getIpAddr(request));
        }
        if (comment.getIdx()==0){
            List<Comment> comments = commentService.queryByFatherByArtid(comment.getArticleId(), 0);
            comment.setIdx(comments.size()+1);
        }else {
            comment.setIdx(comment.getIdx()+0.1);
        }
        if (comment.getIpHome().isEmpty()){
            comment.setIpHome("未知");
        }
        //添加评论
        commentService.save(comment);
        Article byId = articleService.getById(comment.getArticleId());
        if (!loginUser.getUserAccount().equals(byId.getAuthor())){
            //文章总
            Statistic statistic = statisticService.getById(comment.getArticleId());
            statistic.setCommentsNum(statistic.getCommentsNum()+1);
            statisticService.updateById(statistic);
            //积分
            User user = userService.getOne(new QueryWrapper<User>().eq("user_account", loginUser.getUserAccount()));
            Wallet wallet = walletService.getOne(new QueryWrapper<Wallet>().eq("uid", user.getUserId()));
            System.out.println("===>"+wallet.toString());
            walletService.updateById(WalletUtil.ComputeIntegral(wallet,1));
        }
        return "1";
    }


}
